from time import strftime,time
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import re
import pypandoc
import base64
import hmac
import json
import models

# 汉字转拼音
from xpinyin import Pinyin

if Config.CONNECTION.startswith('sqlite'):
    engine = create_engine(
        Config.CONNECTION,
        # echo=True,
        pool_recycle=-1,
        pool_pre_ping=True
    )
else:
    engine = create_engine(
        Config.CONNECTION,
        # echo=True,
        max_overflow=10,
        pool_size=40,
        pool_recycle=-1,
        pool_pre_ping=True
    )


class Config:

    pinyin = Pinyin()


    @staticmethod
    def log(*args, **kwargs):
        print(strftime("[%Y-%m-%d %H:%M:%S] "), *args, **kwargs)

    @staticmethod
    def debug(*args, **kwargs):
        print("DEBUG !!", *args, **kwargs)
    @staticmethod
    def makeNewSession():
        Session = sessionmaker(bind=engine)
        session = Session()
        return session

    @staticmethod
    def safe_file_name(fName):
        return re.sub(r"[^\u4E00-\u9FA5A-Za-z0-9_\.]", '_', fName)



    @staticmethod
    def fieldName(name):
        return Config.pinyin.get_pinyin(name, '_')

    # 计算空格
    @staticmethod
    def calc_space(total:int, use:int, space=' '):
        return space*(total-use)

    # 生成token
    @staticmethod
    def generate_token(key, expire=3600):
        r'''
            @Args:
                key: str (用户给定的key，需要用户保存以便之后验证token,每次产生token时的key 都可以是同一个key)
                expire: int(最大有效时间，单位为s)
            @Return:
                state: str
        '''
        ts_str = str(time() + expire)
        ts_byte = ts_str.encode("utf-8")
        sha1_tshexstr  = hmac.new(key.encode("utf-8"),ts_byte,'sha1').hexdigest() 
        token = ts_str+':'+sha1_tshexstr
        b64_token = base64.urlsafe_b64encode(token.encode("utf-8"))
        return b64_token.decode("utf-8")
    @staticmethod
    def certify_token(key, token):
        r'''
            @Args:
                key: str
                token: str
            @Returns:
                boolean
        '''
        token_str = base64.urlsafe_b64decode(token).decode('utf-8')
        token_list = token_str.split(':')
        if len(token_list) != 2:
            return False
        ts_str = token_list[0]
        if float(ts_str) < time():
            # token expired
            return False
        known_sha1_tsstr = token_list[1]
        sha1 = hmac.new(key.encode("utf-8"),ts_str.encode('utf-8'),'sha1')
        calc_sha1_tsstr = sha1.hexdigest()
        if calc_sha1_tsstr != known_sha1_tsstr:
            # token certification failed
            return False 
        # token certification success
        return True 




    @staticmethod
    def readSettings():
        session = Config.makeNewSession()
        settings_all = session.query(models.Setting).all()
        session.close()
        adict = {}
        for setting in settings_all:
            if setting.type == "str":
                adict[setting.keyname] = setting.value
            elif setting.type == "int":
                adict[setting.keyname] = int(setting.value)
            elif setting.type == "float":
                adict[setting.keyname] = float(setting.value)
            elif setting.type == "Iterable":
                adict[setting.keyname] = json.loads(setting.value)
            else:
                adict[setting.keyname] = setting.value

        return adict



settings = Config.readSettings()

for k,v in settings.items():
    setattr(Config, k, v)

# ## token key
# TOKEN_KEY = "bot token key"
# # 运行端口
# PORT=settings["PORT"]
# # 发送消息给go-cqhttp
# HOST="127.0.0.1"
# SENDPORT=5700
# ROOTDIR = os.path.dirname(__file__)
# # 数据库连接
# CONNECTION = f'sqlite:///{ROOTDIR}/botData.db'
# # f"mysql+pymysql://root:{quote('pwd')}@127.0.0.1:3306/qqbot?charset=utf8",
# # 静态文件目录
# STATIC_PATH = os.path.join(ROOTDIR, 'static')
# # 文件上传下载
# UPLOADDIR = os.path.join(ROOTDIR,"uploadfiles")
# # forms 自定义表单
# FORMDIR = os.path.join(ROOTDIR, "forms")
# FORMPROTOTYPE = os.path.join(FORMDIR, 'form_prototype.html')
# LAYUI_CSS_PATH = os.path.relpath(os.path.join(STATIC_PATH, 'css', 'layui.css'),FORMDIR)
# LAYUI_JS_PATH = os.path.relpath(os.path.join(STATIC_PATH, 'layui.js'),FORMDIR)
# AXIOS_PATH =  os.path.relpath(os.path.join(STATIC_PATH, "js", "axios.min.js"),FORMDIR)
# TABLESELECT_JS = os.path.relpath(os.path.join(STATIC_PATH, "js", "lay-module", "tableSelect","tableSelect.js"),FORMDIR)
# PROTOTYPE_JS = os.path.relpath(os.path.join(STATIC_PATH, "js", "prototype_form.js"),FORMDIR)

# # form表单提交数据
# # FOMR_TABLE_LENGTH = 50
# FORM_UPLOAD_FILES_DIR = os.path.join(ROOTDIR, "formUploadFiles") # 表单提交文件目录

# # # 检验pandoc是否安装
# # pypandoc.ensure_pandoc_installed()

# # 临时zip路径
# ZIP_DIR = os.path.join(ROOTDIR, "zip_dir")
# ZIP_FILE = os.path.join(ZIP_DIR, "temp.zip")
# # 临时 Excel 路径
# EXCEL_PATH = os.path.join(ROOTDIR, "excels", "temp.xlsx") 

# # 主人
# MASTER="1574779559"

# # 外部访问地址
# OUT_ADDRESS = "http://127.0.0.1:5701"

# # Timer
# INTERVAL = 15









